import { GCtrl } from "../../../Core/GCtrl";
import GChild from "../../../Core/GView/GChild";
import { CHAPTERBOX, CMsg } from "../../Common/Define";
import { Res } from "../../Common/UIResources";
import GameMgr from "../../Logic/GameMgr";
import BoxItem from "./BoxItem";

const { ccclass, property, menu, executeInEditMode } = cc._decorator;
@ccclass @menu('Views/Home/ChapterPage')
export default class ChapterPage extends GChild {
    /**加载进度条 */
    @property(cc.ProgressBar) progressBar: cc.ProgressBar = null;

    @property({
        type: cc.Node,
        tooltip: "宝箱图标"
    })
    boxLay: cc.Node = null;

    public setLoadProgress(val: number) {
        if (!this.progressBar) return;
        this.progressBar.progress = Math.min(val, 1);
    }

    protected _storyData: SStoryDataRaw[] = null;
    protected _index: number = null;
    protected _curIsLock: number = CHAPTERBOX.unChapterLock;
    onGLoad() {
        GCtrl.ES.on(CMsg.client.home.onaddLevel, this, this.init.bind(this));
    }



    public initData(datas: SStoryDataRaw[], index: number) {
        //0~6
        this._index = index;
        this._storyData = datas;
        this.init();
    }

    protected init(_d = null, datas = this._storyData) {
        for (let i = 0; i < this.boxLay.children.length; i++) {
            if (this.boxLay.children[i].name == 'BoxItem') {
                this.boxLay.children[i].destroy();
            }
        }
        let level = GameMgr.lUserData.level;
        //当前章节期间已通关关卡
        let curlevel = (level - (datas[0].id - 1));
        let val = (level - (datas[0].id)) / datas.length;
        if (curlevel >= 0) {
            GCtrl.ES.emit(CMsg.client.home.onChangeLevel, this._index);
        }
        if (val >= 1) {
            this.setLoadProgress(1);
            this._curIsLock = CHAPTERBOX.chapterLock;
        } else if (val < 0 && val < -0.08) {
            this.setLoadProgress(0);
            this._curIsLock = CHAPTERBOX.unChapterLock;
        } else {
            this._curIsLock = CHAPTERBOX.chapterLock;
            this.setLoadProgress(val);
        }

        let arr = [];
        datas.forEach((value: SStoryDataRaw, index) => {
            if (value.sectionBox.length > 1) {
                arr.push(index + 1);
                this.assetImpl.prefab(Res.prefab.item.boxItem, (prefab) => {
                    let comp = this.assetImpl.addGChild<BoxItem>(prefab);
                    comp.node.parent = this.boxLay;
                    let val = index / datas.length;
                    let posX = this.progressBar.node.width * val + 23;
                    comp.node.x = posX;
                    comp.initBox(value, index + 1, this._index, curlevel);
                })
            }
        })
    }
}   